package com.lai.dao;

import com.lai.entities.User;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class UserDao {
    @Autowired
    private SessionFactory sessionFactory;

    @Transactional
    public void addUser(User user){
        Session session=sessionFactory.openSession();
        Transaction tx=session.beginTransaction();
        session.save(user);
        tx.commit();
        session.close();
    }

    @Transactional (readOnly = true)
    public User getUserById(int id){
        Session session=sessionFactory.openSession();
        Query query=session.createQuery("from User where id=?");
        query.setInteger(0,id);
        User user=(User)query.uniqueResult();
        return user;
    }
    @Transactional (readOnly = true)
    public User getUserByUsername(String  name){
        Session session=sessionFactory.openSession();
        Query query=session.createQuery("from User where name=?");
        query.setString(0, name);
        User user=(User)query.uniqueResult();
        return user;
    }


    @Transactional (readOnly = true)
    public List<User> listUsers(){
        Session session=sessionFactory.openSession();
        Query query=session.createQuery("from User");
        List<User> users=(List<User>)query.list();
        return users;
    }

}
